package edu.gzhu.guli.back.config;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import lombok.Getter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

@RestControllerAdvice
public class GlobalExceptionHandle extends ResponseEntityExceptionHandler {

  @ExceptionHandler(NoSuchElementException.class)
  public ResponseEntity<Object> handleNoSuchElement(NoSuchElementException ex, WebRequest request) {
    HttpStatus status = HttpStatus.NOT_FOUND;
    final ApiError apiError = ApiError.of(status.value(), ex.getMessage());
    return handleExceptionInternal(ex, apiError, null, status, request);
  }

  @Override
  protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
      HttpHeaders headers, HttpStatus status, WebRequest request) {
    List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
    Map<String, String> fieldErrorsMap = new HashMap<>();
    for (FieldError fieldError : fieldErrors) {
      fieldErrorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
    }
    final ApiError apiError = ApiError.of(status.value(), fieldErrorsMap);
    return handleExceptionInternal(ex, apiError, headers, status, request);
  }

  static class ApiError {
    @Getter
    private final int status;

    @Getter
    private final Object message;

    private ApiError(int status, Object message) {
      this.status = status;
      this.message = message;
    }

    public static ApiError of(int status, Object message) {
      return new ApiError(status, message);
    }
  }
}
